package com.lukebang.controller;

import java.security.interfaces.RSAPrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lukebang.util.BuluResult;
import com.lukebang.constant.Const;
import com.lukebang.pojo.Merchant;
import com.lukebang.pojo.MerchantsWalletRecord;
import com.lukebang.service.IMerchantService;
import com.lukebang.service.MerchantsWalletRecordService;
import com.lukebang.util.JsonUtil;
import com.lukebang.util.RSAUtils;
import com.lukebang.util.jpush.JSMSUtil;

import cn.jsms.api.SendSMSResult;

/**
 * 
 * MerchantForController 上午10:50:14
 * 
 * Copyright zhaocj Inc. All rights reserved. Love ME Like Justin Bieber.
 */

@Controller
@RequestMapping("/merchant")
public class MerchantForController {
	private static Logger logger = LogManager.getLogger(MerchantForController.class.getName());
	@Resource
	private IMerchantService merchantSER;
	@Resource
	private MerchantsWalletRecordService merchantsWalletRecordSER;

	@RequestMapping("/login")
	public @ResponseBody boolean login(String phone, String password, HttpSession session) {
		boolean loginFlag = false;
		try {
			// System.out.println("********************************************"+phone+",密码是："+password);
			String descrypedPwd = null;
			RSAPrivateKey privateKey = (RSAPrivateKey) session.getAttribute("privateKey");
			descrypedPwd = RSAUtils.decryptByPrivateKey(password, privateKey);// 解密后的密码,password
			logger.debug("登录手机是： {}， 密码是： {}", phone, descrypedPwd);
			// System.out.println("********************************************"+phone+",密码是："+descrypedPwd);
			loginFlag = merchantSER.login(phone, descrypedPwd, session);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return loginFlag;
	}

	@RequestMapping("/getWallet")
	public @ResponseBody double getWallet(HttpSession session) {
		return merchantSER.selectWallet(session);
	}

	@RequestMapping("/getInitialInfomation")
	public @ResponseBody Map<String, Object> selectInitialInfomation(HttpSession session) {
		Map<String, Object> retMap = null;
		try {
			retMap = merchantSER.selectInitialInfomation(session);
			//System.out.println("^^^^ 进来了了了 ^^^^^" + retMap);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return retMap;
	}

	@RequestMapping("/logout")
	public String logout(HttpSession session) {
		session.setAttribute(Const.SESSION_USER, null);
		return "redirect:/login.html";
	}

	/**
	 * 00 代表注册成功 11代表验证码有问题
	 * 
	 * @param merchant
	 * @param session
	 * @param checkNum
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/register")
	public @ResponseBody String register(@RequestParam("verifyCode") Integer verifyCode, Merchant merchant,
			HttpSession session) throws Exception {
		logger.debug("传送过来的商户是：{}", JsonUtil.toJson(merchant));
		logger.debug("发送的验证码是：", verifyCode);
		try {
			RSAPrivateKey privateKey = (RSAPrivateKey) session.getAttribute("privateKey");
			String descrypedPwd = RSAUtils.decryptByPrivateKey(merchant.getPassword(), privateKey); // 解密后的密码,password
			merchant.setPassword(descrypedPwd);
			if (verifyCode != null && !("".equals(verifyCode))
					&& verifyCode.equals(session.getAttribute(Const.SESSION_VERIFY_CODE))) {
				int insertKey = merchantSER.insertMerchant(merchant);
				return insertKey == 0 ? "22" : "00";
			} else {
				return "11";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "22";
	}

	@RequestMapping("/sendVerifyCode")
	public @ResponseBody boolean sendVerifyCode(String phone, HttpSession session) {
		logger.debug("需要发送验证码的手机号是：{}", phone);
		// 先判断该手机好是否注册，若注册过则提示用户该手机号已注册，请登录。否则发送验证码；
		// Integer count=merchantSER.selectCountByPhone(phone);
		// if(count==1){
		// session.setAttribute(Const.SESSION_VERIFY_CODE, "手机号已经注册，请直接登录");
		// }else{
		Integer number = (int) (Math.random() * (9999 - 1000 + 1)) + 1000;
		SendSMSResult smsResult = null;
		smsResult = JSMSUtil.sendTemplateSmsToUser(35990, phone, String.valueOf(number), "鹿客帮");
		if (smsResult.isResultOK()) {
			session.setAttribute(Const.SESSION_VERIFY_CODE, number);
			logger.debug("=====已经发送验证码=====" + number);
			return true;
		} else {
			return false;
		}
	}

	@RequestMapping("/isPhoneAlreadyUsed")
	public @ResponseBody Boolean isPhoneAlreadyRegister(String phone) {
		try {
			if (phone != null && !("".equals(phone))) {
				Integer number = merchantSER.selectCountByPhone(phone);
				if (number > 0) {
					return true;
				}
			}
			return false;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return true;
	}

	@RequestMapping("/reset")
	public @ResponseBody boolean reset(Integer verifyCode, Merchant merchant, HttpSession session) throws Exception {
		logger.debug("传送过来的商户是：{}", JsonUtil.toJson(merchant));
		logger.debug("发送的验证码是：", verifyCode);
		try {
			RSAPrivateKey privateKey = (RSAPrivateKey) session.getAttribute("privateKey");
			String descrypedPwd = RSAUtils.decryptByPrivateKey(merchant.getPassword(), privateKey); // 解密后的密码,password
			merchant.setPassword(descrypedPwd);
			if (verifyCode != null && !("".equals(verifyCode))
					&& verifyCode.equals(session.getAttribute(Const.SESSION_VERIFY_CODE))) {
				merchantSER.modifyByPhone(merchant);
				return true;
			} else {
				return false;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	// 查看我的记录
	@RequestMapping("/merchantRecord")
	public String merchantRecord(Model model) {
		model.addAttribute("oneMenu", "wallet");
		model.addAttribute("twoMenu", "merchantRecord");
		return "/cms/wallet/details";
	}

	@RequestMapping("queryMerchantWalletRecord")
	public @ResponseBody Map<String, Object> selectMerchantsRecordDetails(HttpSession session, String recordBeginTime,
			String recordEndTime, Integer indentId, Integer offset, Integer limit, String sort, String order) {
		Map<String, Object> retMap = null;
		try {
			retMap = (Map<String, Object>) merchantsWalletRecordSER
					.selectWorkerWalletRecordByWorkerInfoAndTimeCondition(session, recordBeginTime, recordEndTime,
							indentId, offset, limit, sort, order);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return retMap;

	}

	// 跳转到提现页面
	@RequestMapping("/withDrawalMoney")
	public String repair(Model model) {
		model.addAttribute("oneMenu", "wallet");
		model.addAttribute("twoMenu", "withDrawalMoney");
		return "/cms/wallet/withDrawalMoney";
	}

	/**
	 * 提现啦
	 */
	@RequestMapping("/alipyWithdrawal")
	@ResponseBody
	public BuluResult alipyWithdrawal(HttpServletRequest request, HttpSession session, Double withdrawMoney,
			String zhifubao, String name, Integer status, String password) {
		System.out.println("……^^^^……………………终于进来提现啦啊！…………………………………");
		System.out.println("^^^^^^^" + request + ",,," + session + ",,," + withdrawMoney + ",,," + zhifubao + ",,,"
				+ name + ",,," + status + ",,," + password);
		BuluResult buluResult=new BuluResult();
		buluResult=merchantSER.alipyWithdrawal(request, session, withdrawMoney, zhifubao, name, status,password);
		System.err.println("................"+buluResult);
		return buluResult;
	}
}
